package com.neshai.webapp.controller;

import com.neshai.webapp.entity.AuthRequestEmail;
import com.neshai.webapp.entity.AuthRequestWallet;
import com.neshai.webapp.service.AuthService;
import com.neshai.webapp.service.EmailService;
import com.neshai.webapp.service.VerificationCodeService;
import com.neshai.webapp.utils.JwtUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseCookie;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

import static com.neshai.webapp.utils.EmailUtil.isValidEmail;

@RestController
@RequestMapping({"/api"})
@RequiredArgsConstructor
public class AuthController {
    private final EmailService emailService;
    private final AuthService authService;
    private final VerificationCodeService verificationCodeService;

    @PostMapping("/send-code")
    public String sendVerificationCode(@RequestBody(required = false) Map<String, Object> requestBody) {
        if (requestBody == null || !requestBody.containsKey("email") || requestBody.get("email") == null || requestBody.get("email").toString().trim().isEmpty()) {
            return "invalid email";
        }
        String email = requestBody.get("email").toString();
        if (!isValidEmail(email)) {
            return "invalid email";
        }
        try {
            String code = verificationCodeService.generateCode(email);
            emailService.sendSimpleMessage(email, "Your verification code", "Your verification code is " + code);
        } catch (Exception e) {
            return "send email failure";
        }
        return "Verification code sent";
    }

    @PostMapping("/authenticate/email")
    public ResponseEntity<String> createAuthenticationTokenByEmail(@RequestBody AuthRequestEmail authRequestEmail) throws Exception {
        int userId = authService.emailAuth(authRequestEmail.getEmail(), authRequestEmail.getCode());
        if (userId != -1) {
            final String jwt = JwtUtil.generateToken(userId, authRequestEmail.getEmail(), null);
            ResponseCookie jwtCookie = ResponseCookie.from("jwt", jwt)
                    .httpOnly(false)
                    .secure(false)
                    .path("/")
                    .maxAge(30 * 24 * 60 * 60)  // 30 天
                    .build();

            return ResponseEntity.ok()
                    .header(HttpHeaders.SET_COOKIE, jwtCookie.toString())
                    .body("Login successful");
        } else {
            //throw new Exception("Incorrect verification code");
            return ResponseEntity.badRequest().body("Incorrect verification code");
        }
    }

    @PostMapping("/authenticate/wallet")
    public ResponseEntity<String> createAuthenticationTokenByWallet(@RequestBody AuthRequestWallet authRequestWallet) throws Exception {
        int userId = authService.walletAuth(authRequestWallet.getSignMessage(), authRequestWallet.getMessage(), authRequestWallet.getWalletAddress());
        if (userId != -1) {
            final String jwt = JwtUtil.generateToken(userId, null, authRequestWallet.getWalletAddress());
            ResponseCookie jwtCookie = ResponseCookie.from("jwt", jwt)
                    //设置 HttpOnly 属性为 true，意味着这个 cookie 不能通过 JavaScript 访问，增加了安全性，防止 XSS 攻击。
                    .httpOnly(false)
                    //设置 Secure 属性为 false，意味着这个 cookie 可以通过 HTTP 传输。如果设置为 true，则只有通过 HTTPS 传输时才会发送 cookie。
                    .secure(true)
                    .path("/")
//                    .sameSite("None")
                    .maxAge(30 * 24 * 60 * 60)  // 30 天
                    .build();

            return ResponseEntity.ok()
                    .header(HttpHeaders.SET_COOKIE, jwtCookie.toString())
                    .body("Login successful");
        } else {
            //throw new Exception("Incorrect verification code");
            return ResponseEntity.badRequest().body("error");
        }
    }
}